// pages/Address/edit.js
const Controller = require('../controllers/controllers.js').controller;
const app = getApp();
Page({

    /**
     * 页面的初始数据
     */
    data: {
        // 使用已有地址
        // 当前选择的id
        currentId: '',
        radio: '1',
        //同意条约
        isAgress: false,

        //类型:goods:商品，cart:购物车
        type: "",
        //商品下单
        specs: "",
        goodsId: "",
        goodsSpecAttributePriceIds: "",
        info: {},
        productList:[],
        verification: [],
        //购物车下单
        cartIds: '',
        cartList: [],
        //地址列表
        list: [],
        //价格
        orderPrice: 0,
        discount: 0,
        freight: '',
        //优惠卷id
        userCouponId: '',
        //新增地址
        region: [],
        from: {
            name: "",
            mobile: "",
            province: "",
            city: "",
            area: "",
            address: "",
            isDefault: 0,
            coupon: null,
        }
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {

     let parentid=options.parentid

     let userInfo=wx.getStorageSync('userInfo')
     
      this.data.parentid= parentid&&parentid!=userInfo.id?parentid:''
        if (options.type) {
            this.setData({
                type: options.type
            })
            if (options.type == "goods") {
                let goodsSpecAttributePriceIds=options.goodsSpecAttributePriceIds
                goodsSpecAttributePriceIds=goodsSpecAttributePriceIds.split(',')

                this.setData({
                    goodsId: options.goodsId,
                    goodsSpecAttributePriceIds
                })
                this.getInfo()
            } else {
                this.setData({
                    cartIds: options.cartIds
                })
                this.getCartList()
            }
        }
        app.globalData.coupon = null
    },
    //使用优惠卷
    goCoupon() {
        wx.navigateTo({
            url: '/pages/Pay/coupon',
        })
    },
    //获取地址列表
    getAddressList() {
        Controller.addressList({
            page: 1,
        }).then(res => {
            let goodsIds = ''
            if (this.data.type == "goods") {
                goodsIds = this.data.goodsId
            } else {
                goodsIds = []
                this.data.cartList.forEach(item => {
                    goodsIds.push(item.goodsId)
                })
                goodsIds = goodsIds.join(',')
            }
            let list = res.data.baseData.list
            Controller.freight({
                province: list[0].province,
                goodsIds
            }).then(res => {
                this.setData({
                    currentId: list[0].id,
                    freight: this.data.info.isFreeFreight == 1 ? 0 : res.data.baseData,
                })
            })
            this.setData({
                list,

            })
        })
    },
    goAgreeMent(e){
    let key=e.currentTarget.dataset.key

    if(key){
      wx.navigateTo({
        url: '/pages/agreement/index?key='+key,
      })
    }
    },
    // 新增编辑地址
    golink(e) {
        let name = e.currentTarget.dataset.name
        let id = e.currentTarget.dataset.id
        if (name) {
            wx.navigateTo({
                url: `/pages/Address/edit?type=${name}&id=${id}`,

            })
        }
    },
    //获取购物车
    getCartList() {
        Controller.cartlist().then(res => {
            let cartList = res.data.baseData
            let orderPrice = this.data.orderPrice
            console.log('this.data.cartIds',this.data.cartIds)
            let cartIds=this.data.cartIds
            cartList.forEach(item => {
                item.specsList = item.specs.split(',')
                if(cartIds.indexOf(item.cartId)>-1){
                    orderPrice += (Number(item.discountPrice||0) * item.amount)
                }
                
            })
            cartList = cartList.filter(item => this.data.cartIds.indexOf(item.cartId) != -1)
            this.setData({
                cartList,
                orderPrice
            })
            this.getAddressList()
        })
    },
    //获取商品详情
    getInfo() {
        Controller.goodsdetail({
            goodsId: this.data.goodsId
        }).then(res => {
            let info = res.data.baseData
            let orderPrice=0
            let goodsSpecAttributePriceIds=this.data.goodsSpecAttributePriceIds
            info.specsList = this.data.specs.split(',')
            let verification = info.specAttributePriceList
            let productList=[]
         console.log('goodsSpecAttributePriceIds',goodsSpecAttributePriceIds)
            for(let v of  goodsSpecAttributePriceIds){
                let obj={}

                let index = verification.findIndex(item => item.id === Number(v))
                orderPrice+=verification[index].discountPrice

                obj.specsList=verification[index].desc.split(',')
                obj.imgUrl=verification[index].image||info.imgUrl
                obj.title=info.title
                obj.price=verification[index].discountPrice
                

                productList.push(obj)
               
            }
            console.log('productList==>',productList)

            
          
            
          

            this.setData({
                info,
                productList,
                orderPrice
            })
            this.getAddressList()
        }).catch(err=>{
             console.log('err',err)
        })
    },
    // 选择地址
    selectAddress(e) {
        let currentId = e.currentTarget.dataset.id
        let province = e.currentTarget.dataset.province
        console.log('province',province)
        Controller.freight({
            province
        }).then(res => {
            this.setData({
                currentId,
                freight: this.data.info.isFreeFreight == 1 ? 0 : res.data.baseData,
            })
        })
    },
    // 选择已有地址或者新增地址
    onChange(e) {
        console.log('e==>', e.detail)
        this.setData({
            radio: e.detail
        })
    },
    //输入
    input(e) {
        let name = e.currentTarget.dataset.name
        let from = this.data.from
        from[name] = e.detail.value
        this.setData({
            from
        });
    },

    //Picker改变事件
    bindRegionChange(e) {
        this.setData({
            region: e.detail.value,
        })
    },
    //立刻下单
    subimt() {
        if (!this.data.isAgress) {
            wx.showToast({
                title: '请先勾选同意协议',
                icon: 'none'
            })
            return
        }
        wx.showLoading({
            title: '正在支付',
        })
        if (this.data.type == "goods") {
            this.ordercreate()
        } else {
            this.ordercreateCart()
        }
    },
    //购物车下单
    ordercreateCart() {
     let fn=(addressId)=>{
        Controller.ordercreateCart({
            cartIds: this.data.cartIds,
            userCouponId: this.data.coupon ? this.data.coupon.id : '',
            addressId
        }).then(res => {
            this.pay(res.data.baseData)
        })
     }
        if (this.data.radio == 1) {
            if (!this.data.currentId) {
                wx.showToast({
                    title: '请先选择地址',
                    icon: 'none'
                })
                return
            }

            fn(this.data.currentId)
          
        } else { //新增地址下单
            let from = this.data.from
            let region = this.data.region
            if (!from.name) {
                wx.showToast({
                    title: '姓名不能为空',
                    icon: 'none'
                })
                return
            }
            if (!/^1[0-9]{10}$/.test(from.mobile)) {
                wx.showToast({
                    title: '请输入正确的手机号',
                    icon: 'none'
                })
                return
            }
            if (region.length == 0) {
                wx.showToast({
                    title: '请先选择地区',
                    icon: 'none'
                })
                return
            }
            if (!from.address) {
                wx.showToast({
                    title: '地址不能为空',
                    icon: 'none'
                })
                return
            }
            from.province = region[0]
            from.city = region[1]
            from.area = region[2]
            Controller.addAddress(from).then(res => {
            if(res.code!=0){
                return wx.showToast({
                    title: res.msg,
                    icon:'none'
                  })

            }
             
                
                fn(res.data.baseData)
            })
        }
    },
    //商品下单
    ordercreate() {

    let  fn=(addressId)=>{
        
        let goodsSpecAttributePriceIds=this.data.goodsSpecAttributePriceIds

        if(goodsSpecAttributePriceIds.length>1){

            Controller.ordercreateDouble({
                goodsId: this.data.goodsId,
                amount: 1,
                parentId:this.data.parentid,
                goodsSpecAttributePriceIds: goodsSpecAttributePriceIds.join(','),
                userCouponId: this.data.coupon ? this.data.coupon.id : '',
                addressId
            }).then(res => {
                this.pay(res.data.baseData)
            })
            
          }else{
            Controller.ordercreate({
                goodsId: this.data.goodsId,
                amount: 1,
                parentId:this.data.parentid,
                goodsSpecAttributePriceId: goodsSpecAttributePriceIds.join(','),
                userCouponId: this.data.coupon ? this.data.coupon.id : '',
                addressId
            }).then(res => {
                this.pay(res.data.baseData)
            })

          }
        }
        if (this.data.radio == 1) {
            if (!this.data.currentId) {
                wx.showToast({
                    title: '请先选择地址',
                    icon: 'none'
                })
                return
            }
            fn(this.data.currentId)
        
           
        } else { //新增地址下单
            let from = this.data.from
            let region = this.data.region
            if (!from.name) {
                wx.showToast({
                    title: '姓名不能为空',
                    icon: 'none'
                })
                return
            }
            if (!/^1[0-9]{10}$/.test(from.mobile)) {
                wx.showToast({
                    title: '请输入正确的手机号',
                    icon: 'none'
                })
                return
            }
            if (region.length == 0) {
                wx.showToast({
                    title: '请先选择地区',
                    icon: 'none'
                })
                return
            }
            if (!from.address) {
                wx.showToast({
                    title: '地址不能为空',
                    icon: 'none'
                })
                return
            }
            from.province = region[0]
            from.city = region[1]
            from.area = region[2]
            Controller.addAddress(from).then(res => {

               if(res.code!=0){
                 return wx.showToast({
                     title:res.msg,
                     icon:'none'
                   })
               }
                
                // Controller.ordercreate({
                //     goodsId: this.data.goodsId,
                //     amount: 1,
                
                //     goodsSpecAttributePriceIds: this.data.goodsSpecAttributePriceIds.join(','),
                //     userCouponId: this.data.userCouponId,
                //     addressId: resolve.data.baseData
                // }).then(res => {
                //     this.pay(res.data.baseData)
                // })
               
                fn(res.data.baseData)
            })
        }
    },
    //支付
    pay(orderNumber) {
        Controller.pay({
            orderNumber,
            payType: 1,
           
        }).then(res => {
            let data = res.data.baseData;
            wx.hideLoading()
            wx.requestPayment({
                nonceStr: data.nonceStr,
                package: data.package,
                paySign: data.paySign,
                timeStamp: data.timeStamp,
                signType: data.signType,
                success: (res) => {
                    setTimeout(() => {
                        wx.redirectTo({
                            url: "/pages/Me/Order"
                        })
                    }, 1000)
                    wx.showToast({
                        title: "支付成功",
                        icon: 'none',
                        duration: 1000
                    });
                },
                fail: (res) => {
                    setTimeout(() => {
                        wx.redirectTo({
                            url: "/pages/Me/Order"
                        })
                    }, 1000)
                    wx.showToast({
                        title: "支付失败",
                        icon: 'none',
                        duration: 1000
                    });
                }
            })
        })
    },
    // 选择是否同意条约
    handleAgree(e) {
        this.setData({
            isAgress: !this.data.isAgress
        })
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {
        this.setData({
            coupon: app.globalData.coupon,
            discount: app.globalData.coupon ? app.globalData.coupon.price : 0
        })
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function() {

    }
})